package grape.wx.rest;

import grape.common.exception.ExceptionCode;
import grape.common.exception.runtime.RBaseException;
import grape.common.rest.advice.DisableGRM;
import grape.common.rest.common.ControllerTools;
import grape.common.rest.common.ResultMessage;
import grape.common.tools.ToolService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理
 * Created by yangwei
 * Created at 2020/6/15 11:42
 */
@RestControllerAdvice
@DisableGRM
@Slf4j
@Order(8)
public class WxRestExceptionHandlerAdvice  implements ToolService {


    private ResultMessage createRM(ExceptionCode code, String msg, Object data, Exception e) {
        log.error("请求错误信息: code=[{}],msg=[{}],data=[{}],exceptionMsg=[{}],exception=[{}] ",code, msg, data,e.getMessage(), e.getClass().getName());
        return ControllerTools.newRm(code, msg == null ? code.getMsg() : msg, data);
    }


    /**
     * 微信请求出现的异常
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(WxErrorException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultMessage handleRBaseException(HttpServletRequest request, WxErrorException ex) {
        return createRM(ExceptionCode.fail, ex.getError().getErrorMsg(), ex.getError(), ex);
    }
}
